<template>
    <u-navbar />
    <view class="select-car-page">
        <!-- 车型选择 -->
        <view class="car-type-section">
            <text class="section-title">请选择车型</text>
            <view class="car-type-card">
                <view v-if="carTypes.length">
                    <view v-for="item in carTypes" :key="item.id">
                        <view
                            class="car-type-item"
                            :class="{ active: item.id === selectedCarType }"
                            @click="selectCarType(item.id, item.price)"
                        >
                            <view class="car-image">
                                <image :src="item.image" mode="aspectFill" class="image"></image>
                            </view>
                            <view class="car-info">
                                <view class="car-type">
                                    <text class="xxl bold">{{ item.name }}</text>
                                    <view class="car-description">
                                        <view>
                                            <text class="service">{{ item.service }}</text>
                                            提供服务
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <view class="car-price">
                                ¥
                                <text class="price-text">{{ item.price }}</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view v-else>
                    <text>加载中...</text>
                </view>
            </view>
        </view>

        <!-- 时间选择 -->
        <view class="time-section">
            <text class="section-title">请选择时间</text>
            <view class="picker-item">
                出行时间
                <view>
                    <text>{{ formattedDate }}</text>
                    <u-picker
                        v-model="date_show"
                        mode="time"
                        :params="params"
                        @confirm="onDateConfirm"
                    />
                    <u-icon name="arrow-right" size="24" color="#999" @click="date_show = true" />
                </view>

                <view>
                    <text>{{ formattedHour }}</text>
                    <u-picker
                        v-model="hour_show"
                        mode="selector"
                        :range="selectorObj"
                        :default-selector="[0]"
                        @confirm="onHourConfirm"
                    />
                    <u-icon name="arrow-right" size="24" color="#999" @click="hour_show = true" />
                </view>
            </view>
        </view>

        <!-- 订单预览 -->
        <view class="order-preview">
            <text class="section-title">订单信息</text>
            <view class="order-card">
                <view class="preview-item">
                    <text>出发地：{{ startLocation }}</text>
                </view>
                <view class="preview-item">
                    <text>目的地：{{ endLocation }}</text>
                </view>
                <view class="preview-item" v-if="waypoints.length > 0">
                    <text>途经点：{{ waypoints.map((w) => w.name).join(' → ') }}</text>
                </view>
            </view>
        </view>

        <!-- 预约按钮 -->
        <button class="book-btn commit_btn" @click="submitBooking">立即预约下单</button>
    </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { catTypeAll } from '@/api/car_type'
import UPicker from '@/uni_modules/vk-uview-ui/components/u-picker/u-picker.vue'
import { apiOrderAdd } from '@/api/order'
// 接收上一页参数
const startLocation = ref('')
const endLocation = ref('')
const waypoints = ref([])
const date_show = ref(false)
const hour_show = ref(false)
const carPrice = ref(0)

const params = ref({
    year: true,
    month: true,
    day: true
})

onLoad((options) => {
    if (options.start) {
        startLocation.value = decodeURIComponent(options.start)
    }
    if (options.end) {
        endLocation.value = decodeURIComponent(options.end)
    }
    if (options.waypoints) {
        try {
            waypoints.value = JSON.parse(decodeURIComponent(options.waypoints))
        } catch (e) {
            console.error('解析途经点失败', e)
        }
    }

    getCarTypeList()
})
// 车型列表（可从接口获取）
const carTypes = ref([])
// 当前选择的车型
const selectedCarType = ref(null) // 默认选择第一个
const getCarTypeList = async () => {
    try {
        const res = await catTypeAll()
        if (res && res.length > 0) {
            console.log(typeof res[0].id)
            selectedCarType.value = res[0].id
            carPrice.value = res[0].price
            console.log(typeof selectedCarType.value)
            carTypes.value = res
            await nextTick()
        } else {
            uni.showToast({ title: '暂无车型数据', icon: 'none' })
        }
    } catch (error) {
        uni.showToast({ title: '加载车型失败', icon: 'none' })
        console.error('获取车型失败:', error)
    }
}

// 出行时间
const travelDate = ref({
    year: new Date().getFullYear(),
    month: pad(new Date().getMonth() + 1),
    day: pad(new Date().getDate())
})
// 时间段数据源
const selectorObj = ref([
    '00:00-01:00',
    '01:00-02:00',
    '02:00-03:00',
    '03:00-04:00',
    '04:00-05:00',
    '05:00-06:00',
    '06:00-07:00',
    '07:00-08:00',
    '08:00-09:00',
    '09:00-10:00',
    '10:00-11:00',
    '11:00-12:00',
    '12:00-13:00',
    '13:00-14:00',
    '14:00-15:00',
    '15:00-16:00',
    '16:00-17:00',
    '17:00-18:00',
    '18:00-19:00',
    '19:00-20:00',
    '20:00-21:00',
    '21:00-22:00',
    '22:00-23:00',
    '23:00-00:00'
])
const travelHour = ref(parseInt(`${pad(new Date().getHours())}`))
const formattedDate = computed(() => {
    return `${travelDate.value.year}-${travelDate.value.month}-${travelDate.value.day}`
})

// 格式化时间段显示
const formattedHour = computed(() => {
    return selectorObj.value[travelHour.value] || '请选择时间段'
})

function pad(n) {
    return n < 10 ? '0' + n : n
}

// 车型选择方法
const selectCarType = (id, price) => {
    selectedCarType.value = id
    carPrice.value = price
}

const onDateConfirm = (value) => {
    travelDate.value = value
}

const onHourConfirm = (value) => {
    travelHour.value = value[0]
}

// 提交预约
const submitBooking = async () => {
    if (!selectedCarType.value) {
        uni.showToast({
            title: '请选择车型',
            icon: 'none'
        })
        return
    }
    const waypointsStr = JSON.stringify(waypoints.value)
    const res = await apiOrderAdd({
        order_type: 2,
        car_type_id: selectedCarType.value,
        estimated_time: formattedDate.value + ' ' + formattedHour.value,
        way_address: waypointsStr,
        start_address: startLocation.value,
        end_address: endLocation.value,
        price: carPrice.value
    })
    console.log(res)
}
</script>

<style scoped lang="scss">
.select-car-page {
    padding: 20rpx;
}

.section-title {
    display: flex;
    width: 200rpx;
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    background-image: url('../../static/images/item_bg.png');
    background-repeat: no-repeat;
    background-size: 85% 60%;
    background-position: left 20rpx;
    padding-bottom: 10rpx;
}

.picker-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    border: 1rpx solid #eee;
    border-radius: 16rpx;
    margin-bottom: 40rpx;
    background-color: #ffffff;
}

.order-preview {
    margin-bottom: 60rpx;
}

.order-card {
    background-color: #ffffff;
    padding: 20rpx;
    border-radius: 16rpx;
}

.preview-item {
    display: flex;
    border-bottom: 1rpx solid #f5f5f5;
    padding: 20rpx 0;
}

.book-btn {
    background-color: #07c160;
    color: #fff;
    margin-top: 40rpx;
}

.car-image .image {
    width: 100rpx;
    height: 100rpx;
}

.car-type-card {
    align-items: center;
    justify-content: space-between;
    background: #ffffff;
    padding: 20rpx;
    margin-top: 20rpx;
    border-radius: 16rpx;
}

.car-type-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
}

:deep(.car-type-item.active) {
    border: 1rpx solid #07c160;
    background-image: linear-gradient(to bottom, #fff5de, #ffffff);
    box-shadow: 0 0 8rpx rgba(7, 193, 96, 0.3);
    border-radius: 16rpx;

    .image {
        opacity: 0.8;
    }
}

.car-info {
    margin-left: 20rpx;
    flex: 1;
}

.car-price {
    font-size: 28rpx;
    color: #07c160;
    font-weight: bold;
}

.price-text {
    font-size: 36rpx;
}

.service {
    color: #f9b65b;
}

.time-section {
    margin-top: 20rpx;
}

.section-title {
    background-color: #ffffff;
}
</style>
